package com.atom.app.mvi.net.interceptor

import com.atom.app.mvi.utils.FileUtil
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody.Companion.toResponseBody

class MockInterceptor(private val responseJson: String) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val responseString: String = createResponseBody(chain) ?: return chain.proceed(chain.request())
        return Response.Builder()
            .code(200)
            .message(responseString)
            .request(chain.request())
            .protocol(Protocol.HTTP_1_0)
            .body(responseString.toByteArray().toResponseBody("application/json".toMediaTypeOrNull()))
            .addHeader("content-type", "application/json")
            .build()
    }

    private fun createResponseBody(chain: Interceptor.Chain): String? {
        var responseString: String? = null
        val uri: HttpUrl = chain.request().url
        val path = uri.toUrl().path
        if (path.matches(Regex("^(/users/)+[^/]*+$"))) { //匹配/users/{username}
            responseString = getResponseString("users.json")
        }
        return responseString
    }

    private fun getResponseString(fileName: String): String {
        return FileUtil.readFile(responseJson + fileName, "UTF-8").toString()
    }
}
